package com.baseweb.webadmin.task;

import com.baseweb.webadmin.core.constants.BaseState;
import com.baseweb.webadmin.core.model.pojo.ByUserBizSchedule;
import com.baseweb.webadmin.core.model.pojo.User;
import com.baseweb.webadmin.core.util.CommonUtil;
import com.baseweb.webadmin.core.util.ConfigUtil;
import com.baseweb.webadmin.service.UserOrderService;
import com.baseweb.webadmin.service.UserService;
import org.apache.commons.lang.StringUtils;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Component
public class OrderExpireRemindTask {

    private static final Logger logger = LoggerFactory.getLogger(OrderExpireRemindTask.class);

    @Autowired
    private UserOrderService userOrderService;

    @Autowired
    private UserService userService;

    public void doTask(){
        logger.info("定时任务开始......");
        long begin = System.currentTimeMillis();

        DateTime currentDt = new DateTime();

        DateTime startTime = new DateTime(currentDt.getYear(), currentDt.getMonthOfYear(), currentDt.getDayOfMonth(), 9, 0, 0);

        DateTime endTime = startTime.plusDays(1);

        List<ByUserBizSchedule> byUserBizSchedules = userOrderService.selectScheduleRemindList(null, BaseState.NORMAL.getCode(), startTime, endTime);

        List<Integer> userIds = new ArrayList<Integer>();
        Set set = new HashSet();
        if (byUserBizSchedules != null && byUserBizSchedules.size() > 0){
            for (ByUserBizSchedule current : byUserBizSchedules){
                set.add(current.getUserId());
            }
            userIds.addAll(set);
        }

        if (userIds !=null && userIds.size() > 0) {
            List<User> userList = userService.selectUserByIds(userIds);


            if (userList != null && userList.size() > 0) {
                for (User current : userList) {
                    if (StringUtils.isNotBlank(current.getMobile())) {
                        CommonUtil.sendMessage(current.getMobile(), null, ConfigUtil
                                .getSms_template_code_schedule_remind());

                        try {
                            Thread.sleep(5000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }

        long end = System.currentTimeMillis();
        logger.info("定时任务结束，共耗时：[" + (end-begin) / 1000 + "]秒");
    }

}
